#include "hash.h"

hash::hash(int size):m_hash(NULL), m_size(size)
{
}

hash::~hash()
{
	for (int i = 0; i < m_size; i++)
	{
		if (m_hash[i] != NULL)
		{
			hash_t *cur = m_hash[i];
			hash_t *front = NULL;

			while (cur)
			{
				front = cur->next;
				free(cur->key);
				free(cur);
				cur = front;
			}
		}
	}

	free(m_hash);
	m_hash = NULL;
}

bool hash::init_hash()
{
	m_hash = (hash_t **)malloc(m_size * sizeof(hash_t **));

	memset(m_hash, 0, sizeof(hash_t **) * m_size);

	return true;
}

bool hash::add_hash(hash_t *node)
{
	if (node == NULL)
	{
		return true;
	}

	hash_t *nnode = (hash_t *)malloc(sizeof(hash_t));
	memset((void *)nnode, 0, sizeof(hash_t));

	nnode->key = malloc(node->len);
	memset(nnode->key, 0, node->len);

	memcpy(nnode->key, node->key, node->len);
	nnode->len = node->len;
	nnode->next = NULL;

	int index = 0;
	index = hasher(node->key);

	if (NULL == m_hash[index])
	{
		m_hash[index] = nnode;
	}
	else
	{
		nnode->next = m_hash[index]->next;
		m_hash[index]->next = nnode;
	}

	return true;
}

bool hash::del_hash(hash_t *node)
{
	return true;
}

bool hash::get_hash(hash_t *node)
{
	return true;
}

bool hash::watch_hash()
{
	for (int i = 0; i < m_size; i++)
	{
		if (m_hash[i] == NULL)
		{
			printf("hash[%d] used 0!\n", i);
			printf("*******************\n");
		}
		else
		{
			int cnt = 0;
			hash_t *cur = m_hash[i];
			hash_t *front = NULL;

			while (cur)
			{
				printf("key is: %s\n", (char *)(cur->key));
				cur = cur->next;
				cnt ++;
			}
			printf("hash[%d] used %d!\n", i, cnt);
		}
	}

	return true;  
}

int hash::hasher(void *str)
{
	register unsigned int h = 0;
	register unsigned char *p = NULL;

	for (h = 0, p = (unsigned char *)str; *p; p++)
		h = 31 * h + *p;

	return (h % m_size);
}

